package com.jk.vehicle.mini.util;

import com.jk.vehicle.core.exception.ServiceException;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;

/**
 * @author luoxiaowen
 * @Date 2018/8/28
 */
public class Md5Util {
	/**
	 * 用户密码加密， MD5(userName+password)
	 *
	 * @param password 用户密码
	 * @param userName 用户名
	 * @return MD5加密字符串
	 */
	public static String encryptPassword(String userName, String password) {
		return strToMd5(userName + password);
	}

	/**
	 * MD5加密
	 *
	 * @param str 加密前字符串
	 * @return 加密后字符串
	 */
	private static String strToMd5(String str) {
		String md5Str = null;
		MessageDigest md = null;
		if (str != null && str.length() != 0) {
			try {
				md = MessageDigest.getInstance("MD5");
				md.update(str.getBytes(StandardCharsets.UTF_8));
			} catch (Exception e) {
				throw new ServiceException("加密出错");
			}
			byte[] b = md.digest();
			int i;
			StringBuilder buf = new StringBuilder();
			for (byte aB : b) {
				i = aB;
				if (i < 0) {
					i += 256;
				}
				if (i < 16) {
					buf.append("0");
				}
				buf.append(Integer.toHexString(i));
			}
			md5Str = buf.toString();
		}
		return md5Str;
	}
}

